/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Comments;
import edu.cmu.fithub.db.bean.Posts;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.formbeans.CommentForm;

public class CreateCommentAction extends Action {

	private FormBeanFactory<CommentForm> formFactory = FormBeanFactory
			.getInstance(CommentForm.class);

	public CreateCommentAction() {
	}

	public String getName() {
		return "createComment.do";
	}

	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		try {
			Comments comments = new Comments();
			User user = (User) request.getSession().getAttribute("user");
			CommentForm commentForm = formFactory.create(request);
			if(!commentForm.isPresent()) {
				errors.add("Comment Form is not present!!!");
				return "error.jsp";
			} 
			request.setAttribute("form", commentForm);
			comments.setComment(commentForm.getComment());
			comments.setUser(user);
			comments.setDate(new Date());
			Session dbSession = DBHelper.getSessionFactory().openSession();
			String postId = request.getParameter("postId");
			List<Posts> list = dbSession.createCriteria(Posts.class)
					.add(Restrictions.eq("postId", Integer.parseInt(postId)))
					.list();
			
			errors.addAll(commentForm.getValidationErrors());
			if(errors.size() > 0) {
				return "showComment.do?postId="+postId;
			}
			
			if (list.size() != 0) {
				comments.setPost(list.get(0));
				dbSession.beginTransaction();
				dbSession.save(comments);
				dbSession.getTransaction().commit();
			} else {
				// no such story exists				
				errors.add("No such story Exists!!!");
				return "showComment.do?postId="+postId;
			}
		} catch (FormBeanException e) {
			// handle exception
			errors.add(e.toString());
			return "error.jsp";
		}
		return "commentsuccess.jsp";
	}
}
